package com.yxw.yxnet_cd_center.customer_service.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import com.yxw.yxnet_cd_center.customer_service.dto.PrcAddDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.PrcQueryDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.PrcUpdateDTO;
import com.yxw.yxnet_cd_center.customer_service.entity.YxCsProblemLibEntity;
import com.yxw.yxnet_cd_center.customer_service.mapper.CprMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.PrcMapper;
import com.yxw.yxnet_cd_center.customer_service.service.IPrcService;
import com.yxw.yxnet_cd_center.customer_service.utils.PageUtils;
import com.yxw.yxnet_cd_center.customer_service.utils.UserUtil;
import com.yxw.yxnet_cd_center.customer_service.vo.PrcVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 问题收集管理Service业务层处理
 *
 * @author xiexuxin
 * @date 2023-09-21
 */
@Slf4j
@Service
public class PrcServiceImpl extends ServiceImpl<PrcMapper, YxCsProblemLibEntity> implements IPrcService {

    @Autowired
    private PrcMapper prcMapper;

    @Autowired
    private CprMapper cprMapper;

    @Autowired
    private UserUtil userUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePrcById(Long problemLibId) {
        log.info("开始处理【删除问题】的业务，参数：{}", problemLibId);
        // 查询要删除的问题数据
        PrcVO queryResult = selectPrcById(problemLibId);
        // 判断要删除的问题数据是否存在
        if (queryResult == null || queryResult.getProblemLibId() == 0) {
            throw new BaseException("删除问题失败，尝试删除的问题数据不存在！");
        }
        // 执行删除操作
        int rows = prcMapper.deletePrcById(problemLibId);
        // 判断删除操作是否成功
        if (rows != 1) {
            throw new BaseException("删除问题失败，服务器忙，请稍后再试！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePrcByIds(List<Long> problemLibIds) {
        log.info("开始处理【批量删除问题】的业务，参数：{}", problemLibIds);
        // 判断要删除的问题数据是否存在
        if (problemLibIds == null || problemLibIds.isEmpty()) {
            throw new BaseException("删除问题失败，尝试删除的问题数据不存在！");
        }
        // 执行批量删除操作
        int rows = prcMapper.deletePrcByIds(problemLibIds);
        // 判断删除操作是否成功
        if (rows != problemLibIds.size()) {
            throw new BaseException("删除问题失败，服务器忙，请稍后再试！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePrc(Long problemLibId, PrcUpdateDTO prcUpdateDTO) {
        log.info("开始处理【修改问题】的业务，参数：{}", prcUpdateDTO);
        // 查询要修改的问题
        PrcVO queryResult = prcMapper.selectPrcById(problemLibId);
        // 判断要修改的问题是否存在
        if (queryResult == null || queryResult.getProblemLibId() == 0) {
            throw new BaseException("修改问题失败，尝试修改的岗位数据不存在！");
        }
        // 将更新数据拷贝到实体对象
        YxCsProblemLibEntity prcEntity = new YxCsProblemLibEntity();
        BeanUtils.copyProperties(prcUpdateDTO, prcEntity);
        prcEntity.setProblemLibId(problemLibId);
        prcEntity.setUpdateTime(LocalDateTime.now());
        // 执行更新操作
        int rows = prcMapper.updateById(prcEntity);
        // 判断更新操作是否成功
        if (rows != 1) {
            throw new BaseException("修改问题失败，服务器忙，请稍后再试！");
        }
    }

    @Override
    public PrcVO selectPrcById(Long problemLibId) {
        log.info("开始处理【根据id查询问题】的业务，参数：{}", problemLibId);
        return prcMapper.selectPrcById(problemLibId);
    }

    @Override
    public PageVO<PrcVO> getPrcList(PrcQueryDTO prcQueryDTO) {
        log.info("开始处理【条件查询问题列表】的业务，条件参数：{}", prcQueryDTO);
        // 创建分页对象
        Page<PrcVO> page = new Page<>(prcQueryDTO.getCurrPage(), prcQueryDTO.getPageSize());
        List<PrcVO> list = prcMapper.getPrcList(page,prcQueryDTO);
        // 获取查询结果列表
        for (PrcVO prc : list) {
            Long problemLibId = prc.getProblemLibId();
            String channelName = prc.getChannelName();
            Long channelId = prc.getChannelId();
            updateList(problemLibId, channelName, channelId);
        }
        // 构建分页结果并返回
        return PageUtils.get(page, list);
    }

    @Override
    public List<PrcVO> prcList() {
        log.info("开始处理【查询问题列表】的业务，无参数");
        return prcMapper.prcList();
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateList(Long problemLibId, String channelName, Long channelId) {
        // 根据问题库ID查询问题库实体对象
        YxCsProblemLibEntity problemLib = cprMapper.selectById(problemLibId);
        // 更新问题库实体对象的属性
        problemLib.setChannelName(channelName);
        problemLib.setChannelId(channelId);
        // 执行更新操作
        cprMapper.updateById(problemLib);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addProblem(PrcAddDTO prcAddDTO) {
        log.info("开始处理【收集问题】的业务，参数：{}", prcAddDTO);
        // 创建问题库实体对象，并将prcAddDTO中的属性拷贝到problemLib中
        YxCsProblemLibEntity problemLib = new YxCsProblemLibEntity();
        BeanUtils.copyProperties(prcAddDTO, problemLib);
        if (userUtil.getLoginUserVo() != null){
            String username = userUtil.getLoginUserVo().getUserName();
            problemLib.setLibName(username);
        }
        problemLib.setChannelCode(prcAddDTO.getChannelCode());
        problemLib.setProDes(prcAddDTO.getProDes());
        problemLib.setCreateTime(LocalDateTime.now());
        // 向数据库插入问题库实体对象
        int rows = prcMapper.insert(problemLib);
        // 判断插入是否成功
        if (rows != 1) {
            throw new BaseException("添加问题失败，服务器忙，请稍后再尝试！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void migrateData(List<Long> problemLibIds) {
        log.info("开始处理【常见问题库收录】的业务，参数：{}", problemLibIds);
        // 判断传入的问题库ID列表是否为空或者长度为0
        if (problemLibIds != null && !problemLibIds.isEmpty()) {
            // 根据问题库ID列表从旧表中查询出对应的问题列表
            List<PrcVO> problemList = prcMapper.selectPrcByIds(problemLibIds);
            // 遍历问题列表，向新表中插入记录并更新原始记录的库类型
            for (PrcVO problem : problemList) {
                // 创建新的常见问题库实体对象，将属性值设置为旧问题库对应的属性值
                YxCsProblemLibEntity problemLib = new YxCsProblemLibEntity();
                problemLib.setLibName(problem.getLibName());
                problemLib.setChannelId(problem.getChannelId());
                problemLib.setChannelName(problem.getChannelName());
                problemLib.setChannelCode(problem.getChannelCode());
                problemLib.setProDes(problem.getProDes());
                problemLib.setReplyDes(problem.getReplyDes());
                problemLib.setCreateTime(LocalDateTime.now());
                // 插入常见问题库记录到新表中，并获取问题库ID
                cprMapper.insert(problemLib);
                // 更新旧表中对应记录的库类型为已迁移
                prcMapper.updateLibTypeById(problemLib.getProblemLibId());
            }
            // 删除旧表中已迁移的问题记录
            int rows = prcMapper.deletePrcByIds(problemLibIds);
            // 如果删除的记录数不等于问题库ID列表长度，则表示删除失败，抛出异常
            if (rows != problemLibIds.size()) {
                throw new BaseException("删除问题失败，服务器忙，请稍后再试！");
            }
        }
    }
}
